import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUIStore = defineStore('ui', () => {
  // 面板状态
  const panels = ref({
    leftPanel: {
      visible: true,
      width: 320,
      collapsed: false,
      activeTab: 'tools'
    },
    rightPanel: {
      visible: true,
      width: 320,
      collapsed: false,
      activeTab: 'properties'
    },
    bottomPanel: {
      visible: false,
      height: 200,
      collapsed: false,
      activeTab: 'history'
    }
  })

  // 工具栏状态
  const toolbar = ref({
    visible: true,
    height: 60,
    tools: {
      select: { active: true, visible: true },
      wall: { active: false, visible: true },
      furniture: { active: false, visible: true },
      door: { active: false, visible: true },
      window: { active: false, visible: true },
      text: { active: false, visible: true },
      measure: { active: false, visible: true },
      circuit: { active: false, visible: true },
      annotation: { active: false, visible: true }
    }
  })

  // 状态栏状态
  const statusBar = ref({
    visible: true,
    height: 30,
    items: {
      coordinates: { visible: true, value: 'X: 0, Y: 0' },
      zoom: { visible: true, value: '100%' },
      selection: { visible: true, value: '未选择' },
      mode: { visible: true, value: '设计模式' },
      fps: { visible: false, value: '60 FPS' },
      memory: { visible: false, value: '0 MB' }
    }
  })

  // 模态框状态
  const modals = ref({
    settings: { visible: false, data: null },
    export: { visible: false, data: null },
    import: { visible: false, data: null },
    help: { visible: false, data: null },
    about: { visible: false, data: null }
  })

  // 通知状态
  const notifications = ref([])

  // 上下文菜单状态
  const contextMenu = ref({
    visible: false,
    x: 0,
    y: 0,
    items: [],
    target: null
  })

  // 拖拽状态
  const dragState = ref({
    isDragging: false,
    type: null,
    data: null,
    startPosition: { x: 0, y: 0 },
    currentPosition: { x: 0, y: 0 }
  })

  // 计算属性
  const isLeftPanelVisible = computed(() => panels.value.leftPanel.visible && !panels.value.leftPanel.collapsed)
  const isRightPanelVisible = computed(() => panels.value.rightPanel.visible && !panels.value.rightPanel.collapsed)
  const isBottomPanelVisible = computed(() => panels.value.bottomPanel.visible && !panels.value.bottomPanel.collapsed)
  const isToolbarVisible = computed(() => toolbar.value.visible)
  const isStatusBarVisible = computed(() => statusBar.value.visible)

  const activeTool = computed(() => {
    for (const [toolName, tool] of Object.entries(toolbar.value.tools)) {
      if (tool.active) return toolName
    }
    return 'select'
  })

  const visibleTools = computed(() => {
    return Object.entries(toolbar.value.tools)
      .filter(([_, tool]) => tool.visible)
      .map(([name, _]) => name)
  })

  const visibleStatusItems = computed(() => {
    return Object.entries(statusBar.value.items)
      .filter(([_, item]) => item.visible)
      .map(([name, _]) => name)
  })

  const hasActiveModal = computed(() => {
    return Object.values(modals.value).some(modal => modal.visible)
  })

  const notificationCount = computed(() => notifications.value.length)

  // Actions
  // 面板操作
  const togglePanel = (panelName) => {
    if (panels.value[panelName]) {
      panels.value[panelName].visible = !panels.value[panelName].visible
    }
  }

  const collapsePanel = (panelName) => {
    if (panels.value[panelName]) {
      panels.value[panelName].collapsed = !panels.value[panelName].collapsed
    }
  }

  const setPanelWidth = (panelName, width) => {
    if (panels.value[panelName]) {
      panels.value[panelName].width = Math.max(200, Math.min(500, width))
    }
  }

  const setPanelHeight = (panelName, height) => {
    if (panels.value[panelName]) {
      panels.value[panelName].height = Math.max(100, Math.min(400, height))
    }
  }

  const setPanelTab = (panelName, tabName) => {
    if (panels.value[panelName]) {
      panels.value[panelName].activeTab = tabName
    }
  }

  // 工具栏操作
  const setActiveTool = (toolName) => {
    // 先取消所有工具的激活状态
    Object.values(toolbar.value.tools).forEach(tool => {
      tool.active = false
    })
    
    // 激活指定工具
    if (toolbar.value.tools[toolName]) {
      toolbar.value.tools[toolName].active = true
    }
  }

  const toggleToolVisibility = (toolName) => {
    if (toolbar.value.tools[toolName]) {
      toolbar.value.tools[toolName].visible = !toolbar.value.tools[toolName].visible
    }
  }

  const setToolbarVisible = (visible) => {
    toolbar.value.visible = visible
  }

  // 状态栏操作
  const updateStatusItem = (itemName, value) => {
    if (statusBar.value.items[itemName]) {
      statusBar.value.items[itemName].value = value
    }
  }

  const toggleStatusItemVisibility = (itemName) => {
    if (statusBar.value.items[itemName]) {
      statusBar.value.items[itemName].visible = !statusBar.value.items[itemName].visible
    }
  }

  const setStatusBarVisible = (visible) => {
    statusBar.value.visible = visible
  }

  // 模态框操作
  const showModal = (modalName, data = null) => {
    if (modals.value[modalName]) {
      modals.value[modalName].visible = true
      modals.value[modalName].data = data
    }
  }

  const hideModal = (modalName) => {
    if (modals.value[modalName]) {
      modals.value[modalName].visible = false
      modals.value[modalName].data = null
    }
  }

  const hideAllModals = () => {
    Object.keys(modals.value).forEach(modalName => {
      hideModal(modalName)
    })
  }

  // 通知操作
  const addNotification = (notification) => {
    const id = generateId()
    const newNotification = {
      id,
      type: 'info',
      title: '',
      message: '',
      duration: 5000,
      timestamp: Date.now(),
      ...notification
    }
    
    notifications.value.push(newNotification)
    
    // 自动移除通知
    if (newNotification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, newNotification.duration)
    }
    
    return id
  }

  const removeNotification = (id) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index !== -1) {
      notifications.value.splice(index, 1)
    }
  }

  const clearNotifications = () => {
    notifications.value = []
  }

  const showSuccess = (message, title = '成功') => {
    return addNotification({
      type: 'success',
      title,
      message
    })
  }

  const showError = (message, title = '错误') => {
    return addNotification({
      type: 'error',
      title,
      message,
      duration: 8000
    })
  }

  const showWarning = (message, title = '警告') => {
    return addNotification({
      type: 'warning',
      title,
      message,
      duration: 6000
    })
  }

  const showInfo = (message, title = '信息') => {
    return addNotification({
      type: 'info',
      title,
      message
    })
  }

  // 上下文菜单操作
  const showContextMenu = (x, y, items, target = null) => {
    contextMenu.value = {
      visible: true,
      x,
      y,
      items,
      target
    }
  }

  const hideContextMenu = () => {
    contextMenu.value.visible = false
  }

  // 拖拽操作
  const startDrag = (type, data, x, y) => {
    dragState.value = {
      isDragging: true,
      type,
      data,
      startPosition: { x, y },
      currentPosition: { x, y }
    }
  }

  const updateDrag = (x, y) => {
    if (dragState.value.isDragging) {
      dragState.value.currentPosition = { x, y }
    }
  }

  const endDrag = () => {
    dragState.value = {
      isDragging: false,
      type: null,
      data: null,
      startPosition: { x: 0, y: 0 },
      currentPosition: { x: 0, y: 0 }
    }
  }

  // 布局操作
  const resetLayout = () => {
    panels.value = {
      leftPanel: {
        visible: true,
        width: 320,
        collapsed: false,
        activeTab: 'tools'
      },
      rightPanel: {
        visible: true,
        width: 320,
        collapsed: false,
        activeTab: 'properties'
      },
      bottomPanel: {
        visible: false,
        height: 200,
        collapsed: false,
        activeTab: 'history'
      }
    }
    
    toolbar.value = {
      visible: true,
      height: 60,
      tools: {
        select: { active: true, visible: true },
        wall: { active: false, visible: true },
        furniture: { active: false, visible: true },
        door: { active: false, visible: true },
        window: { active: false, visible: true },
        text: { active: false, visible: true },
        measure: { active: false, visible: true },
        circuit: { active: false, visible: true },
        annotation: { active: false, visible: true }
      }
    }
    
    statusBar.value = {
      visible: true,
      height: 30,
      items: {
        coordinates: { visible: true, value: 'X: 0, Y: 0' },
        zoom: { visible: true, value: '100%' },
        selection: { visible: true, value: '未选择' },
        mode: { visible: true, value: '设计模式' },
        fps: { visible: false, value: '60 FPS' },
        memory: { visible: false, value: '0 MB' }
      }
    }
  }

  const saveLayout = () => {
    const layout = {
      panels: panels.value,
      toolbar: toolbar.value,
      statusBar: statusBar.value,
      timestamp: Date.now()
    }
    
    localStorage.setItem('designer-layout', JSON.stringify(layout))
  }

  const loadLayout = () => {
    const savedLayout = localStorage.getItem('designer-layout')
    if (savedLayout) {
      try {
        const layout = JSON.parse(savedLayout)
        panels.value = layout.panels || panels.value
        toolbar.value = layout.toolbar || toolbar.value
        statusBar.value = layout.statusBar || statusBar.value
      } catch (error) {
        console.error('加载布局失败:', error)
      }
    }
  }

  // 辅助函数
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  return {
    // 状态
    panels,
    toolbar,
    statusBar,
    modals,
    notifications,
    contextMenu,
    dragState,
    
    // 计算属性
    isLeftPanelVisible,
    isRightPanelVisible,
    isBottomPanelVisible,
    isToolbarVisible,
    isStatusBarVisible,
    activeTool,
    visibleTools,
    visibleStatusItems,
    hasActiveModal,
    notificationCount,
    
    // Actions
    togglePanel,
    collapsePanel,
    setPanelWidth,
    setPanelHeight,
    setPanelTab,
    setActiveTool,
    toggleToolVisibility,
    setToolbarVisible,
    updateStatusItem,
    toggleStatusItemVisibility,
    setStatusBarVisible,
    showModal,
    hideModal,
    hideAllModals,
    addNotification,
    removeNotification,
    clearNotifications,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    showContextMenu,
    hideContextMenu,
    startDrag,
    updateDrag,
    endDrag,
    resetLayout,
    saveLayout,
    loadLayout
  }
})
